package com.ssyshop.info.utils;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ssyshop.info.R;
import com.ssyshop.info.view.SelfDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class UpdateManager {
	private Context mContext;

	// 返回的安装包url
	private String apkUrl = "";

	/* 下载包安装路径 */
	@SuppressLint("SdCardPath")
	private static String savePath = "/sdcard/green/";// traceback
	private static String savePath2 = "/sdcard1/green/";

	private static final String saveFileName = savePath + "update.apk";
	private static final String saveFileName2 = savePath2 + "update.apk";

	/* 进度条与通知ui刷新的handler和msg常量 */
	private ProgressBar mProgress;

	private static final int DOWN_UPDATE = 1;

	private static final int DOWN_OVER = 2;

	private int progress;

	private Thread downLoadThread;

	private boolean interceptFlag = false;

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_UPDATE:
				mProgress.setProgress(progress);
				progress_txt.setText(progress+" %");
				break;
			case DOWN_OVER:
				installApk();
				break;
			default:
				break;
			}
		};
	};

	public UpdateManager(Context context) {
		this.mContext = context;
		this.apkUrl = Config.UpDate_URL;
		savePath= Environment.getExternalStorageDirectory().getAbsolutePath() +"/green/";
		//savePath2=Environment.getExternalStorageDirectory().getAbsolutePath() +"/green/";
	}

	// 外部接口让主Activity调用
	public void checkUpdateInfo() {

		showNoticeDialog();
	}

	private SelfDialog selfDialog;
	private void showNoticeDialog() {
		selfDialog=new SelfDialog(mContext,0);//默认为0,  1：只有一个按钮
		selfDialog.setTitle("系统提示");
		selfDialog.setMessage("软件有新版本更新\r\n"+Config.newVerName);
		selfDialog.setYesOnclickListener("下载", new SelfDialog.onYesOnclickListener() {
			@Override
			public void onYesClick() {
				selfDialog.dismiss();
				showDownloadDialog();
			}
		});
		selfDialog.setNoOnclickListener("以后再说", new SelfDialog.onNoOnclickListener() {
			@Override
			public void onNoClick() {
				selfDialog.dismiss();
				Intent intent=new Intent();
				intent.setAction(Config.BROADCAST_LOAD);
				mContext.sendBroadcast(intent);
			}
		});
		selfDialog.show();

	}


	//弹出下载对话框
	private AlertDialog dialog;
	private TextView no_pop;
	private TextView progress_txt;
	private void showDownloadDialog() {
		AlertDialog.Builder builder=new AlertDialog.Builder(mContext);
		LayoutInflater factory = LayoutInflater.from(mContext);
		// 把activity_login中的控件定义在View中
		View view = factory.inflate(R.layout.progress_download, null);
		no_pop= (TextView) view.findViewById(R.id.no_pop);
		progress_txt= (TextView) view.findViewById(R.id.progress_txt);
		mProgress= (ProgressBar) view.findViewById(R.id.progress);
		no_pop.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				interceptFlag = true;
				Intent intent=new Intent();
				intent.setAction(Config.BROADCAST_LOAD);
				mContext.sendBroadcast(intent);
			}
		});
		builder.setView(view);
		dialog=builder.create();
		dialog.setCanceledOnTouchOutside(false);
		// AlertDialog自定义界面圆角有背景问题 有白色背景，加这句代码
		Window window=dialog.getWindow();
		window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
		dialog.show();
		downloadApk();
	}

	private Runnable mdownApkRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				URL url = new URL(apkUrl);
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.connect();
				int length = conn.getContentLength();
				InputStream is = conn.getInputStream();
				boolean isSuc = false;
				File file = new File(savePath);
				File ApkFile;
				if (!file.exists()) {
					isSuc = file.mkdir();
					if (isSuc) {
						String apkFile = saveFileName;
						ApkFile = new File(apkFile);
					} else {
						File file2 = new File(savePath2);
						if (!file2.exists()) {
							isSuc = file2.mkdir();
						}
						String apkFile = saveFileName2;
						ApkFile = new File(apkFile);
					}
				} else {
					String apkFile = saveFileName;
					ApkFile = new File(apkFile);

				}
				FileOutputStream fos = new FileOutputStream(ApkFile);

				int count = 0;
				byte buf[] = new byte[1024];

				do {
					int numread = is.read(buf);
					if(numread!=-1){
						count += numread;
					}
					progress = (int) (((float) count / length) * 100);
					// 更新进度
					mHandler.sendEmptyMessage(DOWN_UPDATE);
					if (numread <= 0) {
						// 下载完成通知安装
						mHandler.sendEmptyMessage(DOWN_OVER);
						break;
					}
					fos.write(buf, 0, numread);
				} while (!interceptFlag);// 点击取消就停止下载.

				fos.close();
				is.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	};

	/**
	 * 下载apk
	 * 
	 * @param
	 */

	private void downloadApk() {
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();
	}

	/**
	 * 安装apk
	 * 
	 * @param
	 */
	private void installApk() {
		File apkfile = new File(saveFileName);
		if (!apkfile.exists()) {
			File apkfile2 = new File(saveFileName2);
			if (!apkfile2.exists()) {
				return;
			} else {
				Intent i = new Intent(Intent.ACTION_VIEW);
				i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				i.setDataAndType(Uri.parse("file://" + apkfile2.toString()),
						"application/vnd.android.package-archive");
				mContext.startActivity(i);
			}
		} else {
			Intent i = new Intent(Intent.ACTION_VIEW);
			i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
					"application/vnd.android.package-archive");

//			i.setDataAndType(Uri.parse("file://"+apkfile.getAbsolutePath()),"application/vnd.android.package-archive");
//			i.setDataAndType(Uri.parse("file:///storage/emulated/0/tracesource/update.apk"),"application/vnd.android.package-archive");

			mContext.startActivity(i);
		}
	}

	public void delFile() {
		// Log.i(TAG, "The TempFile(" + currentTempFilePath + ") was deleted.");
		File myFile = new File(saveFileName);
		if (myFile.exists()) {
			myFile.delete();
		}
		File myFile2 = new File(saveFileName2);
		if (myFile2.exists()) {
			myFile2.delete();
		}
	}




}
